package com.yb.project.system.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yb.common.domain.AjaxObject;
import com.yb.common.domain.PageResult;
import com.yb.common.domain.ZTreeV3;
import com.yb.common.utils.StringUtil;
import com.yb.framework.log.annotation.Log;
import com.yb.framework.log.enums.OperateTypeEnum;
import com.yb.framework.security.utils.SecurityUtil;
import com.yb.project.base.controller.BaseController;
import com.yb.project.system.domain.SysMenu;
import com.yb.project.system.domain.SysUser;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping("/system/user")
@Api(tags = "用户管理")
public class SysUserController extends BaseController {
	
	Logger logger = LoggerFactory.getLogger(SysUserController.class.getName());
	
	private static String SYS_USER = "system/user/user";
	private static String SYS_USER_ADD = "system/user/user_add";
	private static String SYS_USER_EDIT = "system/user/user_edit";
	private static String SYS_USER_INFO = "system/user/user_info";
	
	@GetMapping()
	@PreAuthorize("hasAuthority('system:user')")
	public String main() {
		return SYS_USER;
	}
	
	@GetMapping("/add_view")
	@PreAuthorize("hasAuthority('system:user:add')")
	public String addView() {
		return SYS_USER_ADD;
	}
	
	@GetMapping("/edit_view/{id}")
	@PreAuthorize("hasAuthority('system:user:edit')")
	public String editView(@PathVariable("id") Long id, ModelMap model) {
		model.put("sysUser", sysUserService.getById(id));
		model.put("roleIds", StringUtil.list2String(sysUserRoleService.getRoleIdsByUserId(id)));
		return SYS_USER_EDIT;
	}
	
	@GetMapping("/info")
	//@PreAuthorize("hasAuthority('system:user:info')")
	public String infoView(ModelMap model) {
		model.put("sysUser", sysUserService.getByUsername(SecurityUtil.getUsername()));
		return SYS_USER_INFO;
	}
	
	/**
	 * 用户列表
	 */
	@PostMapping("/list")
	@PreAuthorize("hasAuthority('system:user:list')")
	@ApiOperation(value="分页查询", notes="分页查询用户信息")
	public @ResponseBody PageResult list(SysUser sysUser) {
		startPage();
		ArrayList<SysUser> sysUserList = new ArrayList<SysUser>();
		List<SysUser> userList = sysUserService.getPageByEntity(sysUser);
		for (SysUser user : userList) {
			List<String> roleNames = sysUserService.getRolesByUsername(user.getUsername());
			user.setRoleNames(StringUtil.list2String(roleNames));
			sysUserList.add(user);
		}
		return getPageInfo(sysUserList);
	}
	
	/**
	 * 新增用户
	 */
	@PostMapping("/add")
	@PreAuthorize("hasAuthority('system:user:add')")
	@ApiOperation(value="新增用户", notes="新增用户信息")
	@Log(label = "新增用户", operateType = OperateTypeEnum.ADD)
	public @ResponseBody AjaxObject add(SysUser sysUser) {
		sysUserService.insertUser(sysUser);
		return AjaxObject.newOk("新增用户[" + sysUser.getUsername() + "]，操作成功");
	}
	
	/**
	 * 编辑用户
	 */
	@PostMapping("/edit")
	@PreAuthorize("hasAuthority('system:user:edit')")
	@ApiOperation(value="编辑用户", notes="编辑用户信息")
	@Log(label = "编辑用户", operateType = OperateTypeEnum.EDIT)
	public @ResponseBody AjaxObject edit(SysUser sysUser) {
		sysUserService.updateUser(sysUser);
		return AjaxObject.newOk("编辑用户[" + sysUser.getUsername() + "]，操作成功");
	}
	
	/**
	 * 编辑密码
	 */
	@PostMapping("/modify_password")
	@ApiOperation(value="编辑密码", notes="编辑用户密码")
	@Log(label = "编辑密码", operateType = OperateTypeEnum.EDIT)
	public @ResponseBody AjaxObject modifyPassword(SysUser sysUser) {
		sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
		sysUserService.update(sysUser);
		return AjaxObject.newOk("编辑用户[" + sysUser.getUsername() + "]密码，操作成功");
	}
	
	/**
	 * 删除用户
	 */
	@PostMapping("/delete")
	@PreAuthorize("hasAuthority('system:user:delete')")
	@ApiOperation(value="删除用户", notes="批量删除用户信息")
	@Log(label = "删除用户", operateType = OperateTypeEnum.DELETE)
	public @ResponseBody AjaxObject delete(@RequestParam("ids") String ids) {
		List<String> sysUserNames = sysUserService.getNamesByIds(StringUtil.str2LongArray(ids));
		return toAjax(sysUserService.deleteListByIds(StringUtil.str2LongArray(ids)), "批量删除用户" + sysUserNames);
	}
	
	/**
	 * 根据用户ID，生成菜单树
	 */
	@GetMapping("/menu_tree/{id}")
	public @ResponseBody List<ZTreeV3> sysMenuTree(@PathVariable("id") Long id) {
		List<ZTreeV3> zTreeList = new ArrayList<ZTreeV3>();
		List<SysMenu> sysMenuList = new ArrayList<SysMenu>();
		String username = sysUserService.getById(id).getUsername();
		if("root".equals(username) || "admin".equals(username)) {
			sysMenuList = sysMenuService.getAll();
		} else {
			List<Long> menuIds = sysUserRoleService.getMenuIdsByUserId(id);
			for (SysMenu sysMenu : sysMenuService.getAll()) {
				if(menuIds.contains(sysMenu.getId())) {
					sysMenuList.add(sysMenu);
				}
			}
		}
		if(sysMenuList != null && sysMenuList.size() > 0) {
			for (SysMenu sysMenu : sysMenuList) {
				ZTreeV3 zTree = new ZTreeV3();
				zTree.setId(String.valueOf(sysMenu.getId()));
				zTree.setpId(String.valueOf(sysMenu.getPid()));
				zTree.setName(sysMenu.getText());
				zTree.setIcon(sysMenu.getIconCls());
				zTree.setChecked(true);
				zTreeList.add(zTree);
			}
		}
		return zTreeList;
	}
}